package org.cc.media.player;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

@SuppressWarnings("resource")
public class ShoutcastPlaylistDigester {
	
	public String getUrlFromId(String id) {
		String pls = "http://yp.shoutcast.com/sbin/tunein-station.pls?id=" + id;
		PlsParser parser = null;
		try {
			parser = new PlsParser(pls);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<String> urls = parser.getUrls();
		for (String url : urls) {
			System.out.println("Url : " + url);
		}
		return urls.get(0).toString();
	}
	
	public InputStream getStreamFromUrl(String url)  {
		InputStream inStream = null;
		try {
			URL streamUrl = new URL(url);

			String host = streamUrl.getHost();
			Integer port = 80;
			if (streamUrl.getPort() > 0) {
				port = streamUrl.getPort();
			}

			SocketAddress sockaddr = new InetSocketAddress(host, port);
			Socket socket = new Socket();
			socket.connect(sockaddr, 3000);
			
			inStream = new BufferedInputStream(socket.getInputStream());
			OutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
			String request = "GET /\nicy-metadata:0\nuser-agent:WinampMPEG/5.09\n\n";
			outStream.write(request.getBytes("utf-8"));
			outStream.flush();
			Thread.sleep(300);
			Boolean hasMoreHeaders = true;
			Map<String, String> headers = new HashMap<String, String>();
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while (hasMoreHeaders) {
				String line = in.readLine();
				if (StringUtils.isEmpty(line)) {
					hasMoreHeaders = false;
				} else {
					if (line.contains("200 OK")) {
						continue;
					} else {
						String[] header = StringUtils.split(line, ":", 2);
						System.out.println(line);
						headers.put(header[0], header[1]);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		return inStream;

	}
	
	public InputStream getStreamFromId(String id) {
		String pls = "http://yp.shoutcast.com/sbin/tunein-station.pls?id=" + id;
		PlsParser parser = null;
		try {
			parser = new PlsParser(pls);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<String> urls = parser.getUrls();
		for (String url : urls) {
			System.out.println("Url : " + url);
		}
		return getStreamFromUrl(urls.get(0));
	}

}

class PlsParser {
    private final BufferedReader reader;

    public PlsParser(String url) throws MalformedURLException, IOException {
        URLConnection urlConnection = new URL(url).openConnection();
        this.reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    }

    public List<String> getUrls() {
        LinkedList<String> urls = new LinkedList<String>();
        while (true) {
            try {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                String url = parseLine(line);
                if (url != null && !url.equals("")) {
                    urls.add(url);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

    private String parseLine(String line) {
        if (line == null) {
            return null;
        }
        String trimmed = line.trim();
        if (trimmed.indexOf("http") >= 0) {
            return trimmed.substring(trimmed.indexOf("http"));
        }
        return "";
    }
}
